package ch02.classPath.Entry;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Entry 的实现类
 * 根据组合模式，CompositeEntry 是 Entry 的容器.
 * 可以包含多个不同种类的 Entry 实例，让用户在使用 CompositeEntry 跟普通的 Entry 一致.
 *
 */
public class CompositeEntry extends Entry{
    private List<Entry> entries;
    private String pathList;

    public CompositeEntry(){
        entries = new ArrayList<>();
    }

    public CompositeEntry(String pathList) throws ClassNotFoundException {
        this.pathList = pathList;
        String[] strs = pathList.split(Entry.pathListSeparator);
        entries = new ArrayList<>();

        for (int i=0;i<strs.length;i++){
            entries.add( Entry.createEntry(strs[i]));
        }


    }

    @Override
    public byte[] readClass(String className) throws IOException {
        for (int i=0;i<entries.size();i++){
            byte[] classData = entries.get(i).readClass(className);
            if(classData != null){
                return classData;
            }
        }
        return null;
    }

    @Override
    public String string() {
        return pathList;
    }

    public void addEntry(Entry entry){
        entries.add(entry);
    }


    public static void main(String[] args) {
        String str = "F:\\mine-jvm\\out\\production\\mine-jvm\\ch01;F:\\mine-jvm\\out\\production\\mine-jvm\\ch02\\classPath\\Entry";

        try {
            Entry entry = new CompositeEntry(str);
            byte[] classData = entry.readClass("Entry.class");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
